package com.wiscamp.ninechapters.problems.infrastructure.gateway;

import com.wiscamp.ninechapters.panels.application.services.RoleAppService;
import com.wiscamp.ninechapters.panels.application.services.UserAppService;
import com.wiscamp.ninechapters.problems.domain.gateway.UserGateway;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class UserGatewayImpl implements UserGateway {

    private final UserAppService userAppService;

    private final RoleAppService roleAppService;
    public UserGatewayImpl(UserAppService userAppService, RoleAppService roleAppService) {
        this.userAppService = userAppService;
        this.roleAppService = roleAppService;
    }

    // region user
    public long getOrganizationIdByUser(long userId) {
        var user = userAppService.getUser(userId);
        return Objects.isNull(user) ? 0 : user.getOrganizationId();
    }

    public long getFirstChildId(long parentId) {
        return 0;
    }

    public long getUserIdByCode(String userCode, long appId) {
        var user = userAppService.getUserByCode(appId, userCode);
        return Objects.isNull(user) ? 0 : user.getUserId();
    }
    // endregion

    // region role

    public boolean isStudent(long userId) {
        var roles = userAppService.getRolesByUser(userId);
        for (var role : roles) {
            if ("STUDENT".equalsIgnoreCase(role.getRoleCode()))
                return true;
        }
        return false;
    }

    public boolean isParent(long userId) {
        var roles = userAppService.getRolesByUser(userId);
        for (var role : roles) {
            if ("PARENT".equalsIgnoreCase(role.getRoleCode()))
                return true;
        }
        return false;
    }

    public boolean isSchoolTeacher(long userId) {
        var roles = userAppService.getRolesByUser(userId);
        for (var role : roles) {
            if ("SCHOOL-TEACHER".equalsIgnoreCase(role.getRoleCode()))
                return true;
        }
        return false;
    }

    public boolean isAdministrator(long userId) {
        var roles = userAppService.getRolesByUser(userId);
        for (var role : roles) {
            if ("ITEMBANK-ADMIN".equalsIgnoreCase(role.getRoleCode()))
                return true;
        }
        return false;
    }

    public long getRoleIdByCode(String roleCode, long appId) {
        var role = roleAppService.getRoleByCode(appId, roleCode);
        return Objects.isNull(role) ? 0 : role.getRoleId();
    }
    // endregion
}
